package com.huyun.web.modules.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @ author huyunqiang
 * @ Date 2019/5/28 18:52
 */

public class ReflectTest {
        public static void main(String[] args) throws Exception {

            Class clazz = null;
            Field field = null;
            clazz = Class.forName("com.huyun.web.modules.reflect.Fruit");
            //获取构造器
            Constructor<Fruit> constructor1 = clazz.getConstructor();
            Constructor<Fruit> constructor2 = clazz.getConstructor(String.class);
            Fruit fruit1 = constructor1.newInstance();
            Fruit fruit2 = constructor2.newInstance("Apple");

            //获取属性
            field = clazz.getDeclaredField("type");     //获取私有 type 属性
            field.setAccessible(true);  //对私有字段的访问取消检查
            Fruit fruit = (Fruit) clazz.newInstance();  //创建无参对象实例
            field.set(fruit,"Apple");   //为无参对象实例属性赋值
            Object type = field.get(fruit); //通过 fruit 对象获取属性值

            System.out.println(type);


        }
}
